// Simple MobX implementation

// Store all dependencies and observers
const store = {
    observers: new Map(),
    computedValues: new Map(),
    currentObserver: null
};

// Make a value observable
function observable(target) {
    return new Proxy(target, {
        get(target, key) {
            // Track dependencies
            if (store.currentObserver) {
                if (!store.observers.has(target)) {
                    store.observers.set(target, new Map());
                }
                if (!store.observers.get(target).has(key)) {
                    store.observers.get(target).set(key, new Set());
                }
                store.observers.get(target).get(key).add(store.currentObserver);
            }
            return target[key];
        },
        set(target, key, value) {
            target[key] = value;
            // Notify observers
            if (store.observers.has(target) && store.observers.get(target).has(key)) {
                store.observers.get(target).get(key).forEach(observer => observer());
            }
            return true;
        }
    });
}

// Auto-run function when dependencies change
function autorun(fn) {
    const run = () => {
        store.currentObserver = run;
        fn();
        store.currentObserver = null;
    };
    run();
}

// Computed values
function computed(fn) {
    let value;
    let isComputed = false;

    const computer = () => {
        isComputed = true;
        store.currentObserver = computer;
        value = fn();
        store.currentObserver = null;
        return value;
    };

    return {
        get() {
            if (!isComputed) {
                return computer();
            }
            return value;
        }
    };
}

// Example usage:
const state = observable({
    count: 0,
    price: 100
});

const total = computed(() => state.count * state.price);

autorun(() => {
    console.log('Count changed:', state.count);
    console.log('Total:', total.get());
});

// Test
state.count = 2; // Will trigger autorun
state.price = 150; // Will trigger autorun